// pages/orderRess/orderRess.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //定义变量储存获取到的详情
    list: '',
    //储存商品详情
    good: '',
    orderPrice: '', // 修改这里，指定初始值
    all: '',
    price: 0,
    // 用户获取用户的优惠券信息存放
    orderCoupon: [],
    order: false,
    finalPrice: 0,
    panduan: false,
    dengdai: true,
    // 会员价
    memberPrice: 0,
    member: 0, // 默认0不是会员
    totalPrie: 0, // 商品总额
    judge: true,
    deletes: [],
    prompt: []
  },
  //根据订单号和手机后四位查询快递状态
  addes: function () {
    var list = this.data.list; // 订单详情
    console.log(list.trackingNumber)
    var expressNumber = list.trackingNumber.substr(0, 2); // 获取快递号前两位
    console.log("获取快递号前两位")
    console.log(expressNumber);
    if (expressNumber === 'SF') {
      var app = getApp();
      app.globalData.expressage = list;
      wx.navigateTo({
        url: '/pages/logistics/logistics'
      });
    } else {
      wx.showToast({
        title: '暂不支持查询的快递',
        icon: 'none',
        duration: 2000
      });
    }
  },

  handleAppraise: function (event) {
    var app = getApp();
    // 获取当前点击的商品信息（不修改原始订单数组）
    var currentItem = event.currentTarget.dataset.item;
    console.log(currentItem)
    if (typeof currentItem !== 'undefined') {
      console.log('当前评价的商品对象', currentItem);
      // 使用专门的全局变量存储当前评价的商品
      app.globalData.currentAppraiseItem = currentItem;
      // 跳转评价页面，不修改原始订单数组的全局变量
      wx.navigateTo({
        url: `/pages/appraise/appraise?productId=${currentItem.goodsId}&id=${currentItem.id}`
      });
    } else {
      const all = this.data.all[0];
      console.log("单条商品数据", all);
      app.globalData.currentAppraiseItem = all;
      // 跳转评价页面，不修改原始订单数组的全局变量
      wx.navigateTo({
        url: `/pages/appraise/appraise?productId=${all.goodsId}&id=${all.id}`
      });
    }
  },

  showConfirmationDialog() {
    let deletes = this.data.deletes
    let prompt = this.data.prompt
    console.log(prompt)
    const result = prompt.join(',');
    if (deletes.length > 0) {
      wx.showModal({
        title: '确认操作',
        content: `您订单中存在已下架商品${result}是否删除，删除后才能正常支付？`,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
            for (let i = 0; i < deletes.length; i++) {
              console.log(deletes[i])
              wx.request({
                url: `https://199shq.com/api/orders/delete/${deletes[i]}`,
                method: 'PUT',
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'token': wx.getStorageSync('token')
                },
                success: (res) => {
                  wx.showToast({
                    title: `删除成功`,
                    icon: '',
                    duration: 2000
                  });
                },
                fail: (error) => {
                  console.log(error); // 请求失败的处理
                }
              });
            }
            wx.navigateTo({
              url: '/pages/pay/pay'
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    }
  },
  //定义函数获取到订单的详情
  getdetail: function () {
    var that = this;
    var app = getApp();
    // 始终从原始订单数组全局变量获取数据
    var item = app.globalData.addid;
    // 用于收集每个商品的 canCoupon 值
    let canCouponList = [];
    console.log("获取到订单的详情", item);
    console.log(item);

    // 判断item是否为数组，不是则转为数组
    if (!Array.isArray(item)) {
      item = item ? [item] : [];
    }

    that.setData({
      all: item
    });
    console.log(that.data.all)
    var prie = 0;
    var totalPrie = 0;

    for (var i = 0; i < item.length; i++) {
      prie = prie + item[i].orderPrice;
      if (item[i].goodsNumber !== undefined && item[i].goodsNumber !== '') {
        totalPrie = totalPrie + item[i].goodsPrice * item[i].goodsNumber;
      } else {
        var toastText = '错误请联系客服';
        wx.showToast({
          title: `${toastText}`,
          icon: 'error',
          duration: 5000
        });
        this.setData({
          order: true
        })
      }
    }
    console.log(totalPrie);
    that.setData({
      price: prie.toFixed(2),
      totalPrie: totalPrie.toFixed(2)
    })
    console.log(that.data.all)
    console.log(item);
    let deletes = []
    let prompt = []
    for (let i = 0; i < item.length; i++) {
      wx.request({
        url: `https://199shq.com/api/orders/details/${item[i].id}`,
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          console.log(res.data.data);
          var list = res.data.data;
          var lists = res.data.data
          if (list == null) {
            var toastText = '存在商品已下架，暂无法支付';
            wx.showToast({
              title: `${toastText}`,
              icon: '',
              duration: 2000
            });
          } else {
            that.setData({
              list: res.data.data
            })
          }
          var goodid = res.data.data.goodsId;
          var ordersSpecName = res.data.data.ordersSpecName
          console.log(ordersSpecName)
          wx.request({
            url: `https://199shq.com/api/tproduct/${goodid}`,
            method: 'GET',
            header: {
              'Content-Type': 'application/json',
              'token': wx.getStorageSync('token')
            },
            success: function (res) {
              var product = res.data.data;
              console.log(product)
              // 把 canCoupon 状态存入数组
              canCouponList.push({
                goodsId: goodid,
                canCoupon: product?.canCoupon,
                goodsName: item[i].goodsName
              });
              if (product == undefined) {
                var toastText = '该商品已删除';
                wx.showToast({
                  title: `${toastText}`,
                  icon: '',
                  duration: 2000
                });
                that.setData({
                  judge: false
                })
              }
              if (lists.orderStatus == 0) {
                if (product.productStatus == 0) {
                  deletes.push(item[i].id)
                  prompt.push(item[i].goodsName)
                  console.log(deletes)
                  console.log(prompt)

                  that.setData({
                    deletes: deletes,
                    prompt: prompt,
                    good: res.data.data,
                    orderPrice: res.data.data.price,
                    judge: false
                  })
                } else {
                  that.setData({
                    good: res.data.data,
                    orderPrice: res.data.data.price
                  })
                }
                if (i === item.length - 1) {
                  console.log('进入')
                  that.showConfirmationDialog()
                }
              } else {
                that.setData({
                  good: res.data.data,
                  orderPrice: res.data.data.price,
                  canCouponList: canCouponList
                })
              }
            }
          })
          wx.request({
            url: `https://199shq.com/api/tproduct/getStockById/${goodid}/${ordersSpecName}`,
            method: 'GET',
            header: {
              'Content-Type': 'application/json',
              'token': wx.getStorageSync('token')
            },
            success: function (res) {
              var list = res.data.data;
              console.log(list.stock)
              if (list.stock <= 0) {
                that.setData({
                  panduan: true
                })
              }
            }
          })
        }
      })

    }
    // 处理会员价
    const userInfo = wx.getStorageSync('userInfo');
    var userId = userInfo.wxUserId;
    var that = this;

    wx.request({
      url: `https://199shq.com/api/wxuser/getMembershipPrice/` + encodeURIComponent(userId),
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.data.member == 1) {
          const data = res.data.data;
          console.log(res);
          const price = that.data.totalPrie
          const memberPrice = data.memberPrice * price;
          console.log(memberPrice);
          that.setData({
            memberPrice: memberPrice.toFixed(2),
            member: data.member,
          });
        }
      },
      fail: (error) => {
        console.log(error); // 请求失败的处理
      }
    });
    that.setData({
      dengdai: false
    })

  },

  //当用户点击了取消订单时在数据库逻辑删除
  delorder: function () {
    var app = getApp();
    var item = app.globalData.addid;
    console.log(item);
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否删除',
      success(res) {
        if (res.confirm) {
          for (var i = 0; i < item.length; i++) {
            wx.request({
              url: `https://199shq.com/api/orders/delete/${item[i].id}`,
              method: 'PUT',
              header: {
                'Content-Type': 'application/json',
                'token': wx.getStorageSync('token')
              },
              success: function (res) {
                console.log(res.data.data);
                var list = res.data.data;
                if (list == null) {
                  var toastText = '数据获取失败';
                  wx.showToast({
                    title: 'toastText',
                    icon: '',
                    duration: 2000
                  });
                } else {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
        } else if (res.cancel) {
          return false
        }
      }
    })
  },
  delorder1() {
    wx.navigateTo({
      url: '/pages/service/service'
    });
  },

  delorder2() {
    var that = this;
    let judge = that.data.judge
    let order = that.data.order
    let panduan = that.data.panduan
    let dengdai = that.data.dengdai
    console.log(judge)
    if (order) {
      var toastText = '暂无法支付';
      wx.showToast({
        title: `${toastText}`,
        icon: 'error',
        duration: 2000
      });
      return;
    }
    if (panduan) {
      wx.showToast({
        title: `暂无库存`,
        icon: 'error',
        duration: 2000
      });
      return;
    }
    if (dengdai) {
      wx.showToast({
        title: `数据加载中`,
        icon: 'error',
        duration: 2000
      });
      return;
    }
    if (judge) {
      var app = getApp();
      var id = that.data.list.id;
      console.log(app.globalData.addid);
      app.globalData.cat_ID = app.globalData.addid;
      app.globalData.allprice = 0;
      app.globalData.allprice = that.data.price;
      console.log(id);
      wx.navigateTo({
        url: `/pages/pays/pays?value=${id}`,
      })
      console.log(this.data.orderPrice)
    } else {
      this.showConfirmationDialog()
    }
  },

  async delorder3() {
    var that = this;
    // 时间判断（22：00到次日早上8：00限制退款）
    const now = new Date();
    const hour = now.getHours();
    const canCouponList = that.data.canCouponList || [];

    if (hour >= 22) {
      wx.showToast({
        title: '已过申请时间',
        content: '今日申请已截止，请明日 8:00 后再试',
        icon: 'none',
        duration: 2000
      });
      return;
    } else if (hour < 8) {
      wx.showToast({
        title: '暂未开放申请',
        content: '尚未到申请时间，每日 8:00 开放退款申请',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 获取订单商品列表
    const goodsList = that.data.all;
    if (!Array.isArray(goodsList) || goodsList.length === 0) {
      wx.showToast({
        title: '数据异常',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 获取全局订单数据
    const app = getApp();
    const orderItems = app.globalData.addid;
    if (!Array.isArray(orderItems)) {
      wx.showToast({
        title: '订单数据异常',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查是否有商品 canCoupon === 1
    const restrictedItem = canCouponList.find(item => Number(item.canCoupon) === 1);
    if (restrictedItem) {
      wx.showToast({
        title: '优惠券商品不可退款',
        content: `商品【${restrictedItem.goodsName}】使用优惠券购买，不支持自助退款`,
        icon: 'none',
        duration: 3000
      });
      return; // 阻止退款
    }

    // 遍历每个商品，通过 goodsId 请求 tproduct 接口判断 categoriesId
    for (let item of orderItems) {
      const goodsId = item.goodsId;

      // 同步等待接口返回结果
      const isShuYing = await that.checkIfShuYingProduct(goodsId);
      if (isShuYing) {
        wx.showToast({
          title: '术赢产品不可退款',
          content: '包含“术赢”系列产品，不支持自助退款，请联系商家咨询',
          icon: 'none',
          duration: 2500
        });
        return; // 发现术赢产品，立即阻止退款
      }
    }

    let judge = that.data.judge
    if (judge) {
      var item = app.globalData.addid;
      console.log(item);
      wx.showModal({
        title: '提示',
        content: '是否确认申请退款',
        success(res) {
          if (res.confirm) {
            // 获取需要申请退款的订单id
            for (var i = 0; i < item.length; i++) {
              wx.request({
                url: `https://199shq.com/api/orders/status6/${item[i].id}`,
                method: 'PUT',
                header: {
                  'Content-Type': 'application/json',
                  'token': wx.getStorageSync('token')
                },
                success: function (res) {
                  wx.showToast({
                    title: '退款申请成功',
                    icon: 'success',
                    duration: 2000
                  });
                  console.log('退款申请成功');
                },
                fail: function (error) {
                  wx.showToast({
                    title: '退款申请失败',
                    icon: 'none',
                    duration: 2000
                  });
                  console.error('退款申请失败', error);
                }
              });
            }
          }
        }
      })
    } else {
      wx.showModal({
        title: '错误提示',
        content: '存在商品已下架或已删除，如需退款请联系商家。',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了确定');
            wx.navigateBack({
              delta: 1
            });
          }
        }
      });
    }
  },

  copyTrackingNumber: function () {
    const id = this.data.list.id;
    wx.setClipboardData({
      data: id,
      success: function () {
        wx.showToast({
          title: '订单编号已复制',
          icon: 'success'
        });
      },
      fail: function () {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  // 查询用户自己的现金优惠券 orderCoupon用于优惠券
  getUserCoupons: function () {
    var that = this;
    var app = getApp();
    var UserId = String(app.globalData.userInfo.wxUserId);
    console.log("用户id" + UserId)
    wx.request({
      url: `https://199shq.com/api/couponUse/wxUserId/${UserId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        var orderCoupon = res.data.data;
        console.log(orderCoupon);

        var newDataArray = [];
        orderCoupon.forEach(item => {
          console.log(item.status);
          console.log("this.data.storeID" + this.data.storeID);
          console.log("item.storeId" + item.storeId);
          var storeID = parseInt(this.data.storeID);
          var storeId = parseInt(item.storeId);
          if (item.status === 1 && storeID === storeId && item.discountType === 1) {
            newDataArray.push(item);
          }
        });

        console.log(newDataArray);

        this.setData({
          orderCoupon: newDataArray,
        });
        if (newDataArray.length > 0) {
          let finalPrice = this.data.price - orderCoupon[0].discountPrice;
          this.setData({
            finalPrice: finalPrice
          });
        }
      }
    })
  },

  //判断订单是否为术赢
  checkIfShuYingProduct(goodsId) {
    return new Promise((resolve) => {
      wx.request({
        url: `https://199shq.com/api/tproduct/${goodsId}`,
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.data.code === 200 && res.data.data) {
            const categoriesId = res.data.data.categoriesId;
            // 判断是否为术赢分类
            if (categoriesId === 711460724) {
              resolve(true);
            } else {
              resolve(false);
            }
          } else {
            console.error('获取商品详情失败', res);
            resolve(false); // 接口失败，暂不阻止退款
          }
        },
        fail: (err) => {
          console.error('请求商品接口失败', err);
          // 保守处理，网络失败时阻止退款
          resolve(true); // 假设是术赢，防止绕过
        }
      });
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getdetail();
    this.getUserCoupons();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getdetail();
    this.getUserCoupons();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})